package chess;

import java.awt.Color;
import java.util.HashSet;
import java.util.Set;

public class Player {

	private static final int pawnPt= 1;
	private static final int bishopPt= 3;
	private static final int knightPt= 3;
	private static final int rookPt= 5;
	private static final int queenPt= 9;
	private static final int kingPt= Integer.MAX_VALUE;
	private Color color;
	public static int count= 0;

	public Player(Color color){
		this.color= color;
	}

	public int getScore(Coordinate c, Grid g){
		int score= 0;
		Piece old= g.getPiece(c);
		if (old!= null){
			if (old.getType()== "Pawn") score= pawnPt;
			else if (old.getType()== "Bishop") score= bishopPt;
			else if (old.getType()== "Knight") score= knightPt;
			else if (old.getType()== "Rook") score= rookPt;
			else if (old.getType()== "Queen") score= queenPt;
			else score= kingPt;
		}
		return score;
	}

	public Move searchMove(Grid g, Color col){
		count++;
		Set<Piece> pieces = new HashSet<Piece>();
		int maxScore=Integer.MIN_VALUE;
		Move bestMove= null;
		int oppScore;
		for (int i=0; i<GameRunner.X; i++){
			for (int j=0; j<GameRunner.Y; j++){
				Piece p= g.getPiece(i,j);
				if (p!= null && p.getColor()== col) pieces.add(p);
				// pieces is the set of all player's pieces
			}
		}

		for (Piece pp: pieces){
			if (pp.getPossibleCoordinates()!= null){
				for (Coordinate c: pp.getPossibleCoordinates()){
					if (count==4){
						// computer's asking user for high score, which is 0
						oppScore= 0;
						if ((getScore(c,g)- oppScore)> maxScore){
							maxScore= getScore(c,g)- oppScore;
							bestMove= new Move(pp, c, maxScore);
						}
						// returns computer's highest scoring move
						//return bestMove;
					} else {
						oppScore = 0;
						int moveScore= getScore(c,g);
						Coordinate oldCo = pp.getCoordinate();
						Piece oldP= g.getPiece(c);
						pp.setCoordinate(c, g);
						g.setPieceToCoordinate(oldCo, null);
						/*
						if (GameRunner.whiteTurn) {
							if (count%2==1) oppScore = searchMove(g, Color.BLACK).score;
							else oppScore = searchMove(g, Color.WHITE).score;
						} else {
							if (count%2==0) oppScore = searchMove(g, Color.BLACK).score;
							else oppScore = searchMove(g, Color.WHITE).score;
						}
						 */
						if (count%2==1) {
							oppScore = searchMove(g, Color.WHITE).score;
							count--;
						}
						else if (count%2==0) {
							oppScore = searchMove(g, Color.BLACK).score;
							count--;
						}
						
						pp.setCoordinate(oldCo, g);
						if (oldP!= null) oldP.setCoordinate(c, g);
						else g.setPieceToCoordinate(c, null);

						if ((moveScore- oppScore)> maxScore){
							maxScore= moveScore- oppScore;
							bestMove= new Move(pp, c, maxScore);
						}
						//return bestMove;
					}
				}
			}
		}
		//if (count!=0) count= 0;
		return bestMove;
	}
}
